
package cn.edu.nju.ws.sview.mail;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;   
import java.util.Properties;   
import java.util.Date;
import java.util.regex.Pattern;

import javax.activation.DataHandler;   
import javax.activation.FileDataSource; 
import javax.mail.Authenticator;   
import javax.mail.BodyPart;   
import javax.mail.Folder;
import javax.mail.Message;   
import javax.mail.MessagingException;   
import javax.mail.Multipart;   
import javax.mail.PasswordAuthentication;   
import javax.mail.Session;   
import javax.mail.Store;
import javax.mail.Transport;   
import javax.mail.internet.InternetAddress;   
import javax.mail.internet.MimeBodyPart;   
import javax.mail.internet.MimeMessage;   
import javax.mail.internet.MimeMultipart;   

  
  
public class Email { 
	
	/*public static void main(String args[]){
		Email.SendConfirmMail("276947702@qq.com", "ballrivers" );
		for(int i=0;i<10; i++)
		System.out.println(Email.mailaddr("xujiang0804@163.com"));
	}*/
	
	public static void SendConfirmMail(String desID, String userID,String from){
		Email mail=new Email();
		try {
			mail.SendMail("njusview@163.com", "gongsaisai", desID,userID,from);
		} catch (Exception e) {
			System.out.println("The mail address is wrong !");		
		}
	}
	
	public boolean isEmail(String email){ 
		Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); 
		/** 
			 * �ж��ǲ���һ���Ϸ��ĵ����ʼ���ַ 
			 * @param email 
			 * @return 
			 */
		if(email.equals(null)) return false; 
		email = email.toLowerCase(); 
		if(email.endsWith(".con")) return false; 
		if(email.endsWith(".cm")) return false; 
		if(email.endsWith("@gmial.com")) return false; 
		if(email.endsWith("@gamil.com")) return false; 
		if(email.endsWith("@gmai.com")) return false; 
		return emailer.matcher(email).matches(); 
	}
           
    public void SendMail(String strID,String strPassword,String strDesID,String userID,String from) throws Exception {   
        String host = "smtp.163.com";// "smtp.163.com"    
        //String port = "994"; 
        Properties props = new Properties();   
        props.setProperty("mail.smtp.host", host);    
        //props.setProperty("mail.smtp.port", port);   
        props.setProperty("mail.smtp.auth", "true");   
        props.setProperty("mail.smtp.ssl.enable", "true");//"true"   
        props.setProperty("mail.smtp.connectiontimeout", "5000");   

           
        final String user = strID ;  //"***@163.com"   
        final String pwd = strPassword;   
        Session session = Session.getInstance(props, new Authenticator() {    
            protected PasswordAuthentication getPasswordAuthentication() {   
                //��¼�û�������   
                return new PasswordAuthentication(user,pwd);   
            }   
        });   

        session.setDebug(true);   
        Transport transport = session.getTransport("smtps");//"smtps"   
        transport.connect(host,user,pwd);    
        //��Ϣ   
        MimeMessage message = new MimeMessage(session); 
        String htmlContent="<html><head><title></title></head><body>尊敬的 客户 您好：<br>  "+
        					"感谢您使用sview系统。为了激活您的账号，请点击下面链接<br>"+
        					"  <a href = 'http://ws.nju.edu.cn/sview/register.do?code="+userID+"&from="+from+"'>"+
        					"http://ws.nju.edu.cn/sview/register.do?code="+userID+"&from="+from+
        						"</a><br>请在24小时之内激活账号，过期将作废</body></html>";
        message.setContent(htmlContent,"text/html;charset=gb2312");
        
        message.setSubject("SView账号激活");   
        //��Ϣ�����߽���������   
        message.setFrom(new InternetAddress(user,"The SView website"));    
        message.addRecipients(Message.RecipientType.TO,new InternetAddress[]{   
                new InternetAddress(strDesID)
        });   
        message.saveChanges();   
           
        //����   
        Transport.send(message);   
           
        transport.close();     
           
    }   
       
    //**�趨�ʼ�����   
    private void setMailContent(MimeMessage message,String messageContent) throws MessagingException {   
        //����һ��ֻ���ı��ʼ�   
        //message.setText("Welcome to java");//���ı�����   
        //����������Ӹ������ʼ�   
        Multipart part = new MimeMultipart();   
           
        BodyPart bodypart1 = new MimeBodyPart();   
        bodypart1.setText(messageContent);         
        part.addBodyPart(bodypart1 );            
        message.setContent(part); 
    }
    
	public static String generateCode(int length){
		 char[] ss = new char[length];
		 int[] flag = {0,0,0}; //A-Z, a-z, 0-9
		 int i=0;
		 while(flag[0]==0 || flag[1]==0 || flag[2]==0 || i<length) {
		    i = i%length;
		    int f = (int) (Math.random()*3%3);
		    if(f==0)  
		    	ss[i] = (char) ('A'+Math.random()*26);
		    else if(f==1)  
		    	ss[i] = (char) ('a'+Math.random()*26);
		    else 
		    	ss[i] = (char) ('0'+Math.random()*10);    
		    flag[f]=1;
		    i++;
		 }
		 return new String(ss);
	}
	
	public static String mailaddr(String email){
		if(email==null){ 
			System.out.println("email is null");
			return null;
		}
		int i=email.indexOf('@');
		if(email.substring(i+1).equals("gmail.com")) return "gmail.google.com";
		else return "mail."+email.substring(i+1);
	}

}